<?php
/**
 * Created by PhpStorm.
 * User: lx
 * Date: 2020/1/14
 * Time: 15:22
 */
namespace app\http\middleware;

use app\util\ReturnCode;
use think\cache\driver\Redis;

class MtApiToken
{
    /*
     * @todo
     */
    public function handle($request, \Closure $next) {
        if(config("apiadmin.CHECK_USER_TOKEN")){
            $token = $request->param('token'); // 传参token
            if(!$token){
                return json([
                    'code' => ReturnCode::EMPTY_PARAMS,
                    'msg'  => '请先登录',
                    'data' => []
                ]);
            }
            $redisTokenID = (new Redis)->get($token); // 用token获取redis中用户ID
            if(!$redisTokenID){
                return json([
                    'code' => ReturnCode::RECORD_NOT_FOUND,
                    'msg'  => 'token过期,请重新登录!',
                    'data' => []
                ]);
            }
            $redisToken = (new Redis)->get("userToken".$redisTokenID); //用用户id获取redis中token
            if($token != $redisToken){ //比对两个token
                return json([
                    'code' => ReturnCode::RECORD_NOT_FOUND,
                    'msg'  => 'token过期,请重新登录。',
                    'data' => []
                ]);
            }
            (new Redis)->set("userToken".$redisTokenID,$token,600); // token存储
            (new Redis)->set($token,$redisTokenID,600); // 登录状态
        }
        return $next($request);
    }
}